package com.ihcy.beancopy.config;

import com.ihcy.beancopy.dto.OriginClass;
import com.ihcy.beancopy.dto.OriginOrder;
import com.ihcy.beancopy.dto.TargetClass;
import com.ihcy.beancopy.dto.TargetOrder;
import com.ihcy.beancopy.service.convert.CodeEnumConvert;
import com.ihcy.beancopy.service.convert.StringDateConverter;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OrikaConfig {

    @Autowired
    private StringDateConverter stringDateConverter;
    @Autowired
    private CodeEnumConvert codeEnumConvert;

    @Bean
    public MapperFactory getFactory(){
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        mapperFactory.getConverterFactory().registerConverter("stringDateConverter",stringDateConverter);
        mapperFactory.getConverterFactory().registerConverter("codeEnumConvert",codeEnumConvert);
        orderConvert(mapperFactory);
        classConvert(mapperFactory);
        return mapperFactory;
    }

    private void orderConvert(MapperFactory mapperFactory){
        mapperFactory.classMap(OriginOrder.class, TargetOrder.class)
                .field("name1","name2")
                .fieldMap("stringToDate","stringToDate").converter("stringDateConverter").add()
                .fieldMap("dateToString","dateToString").converter("stringDateConverter").add()
                .byDefault()
                .register();
    }

    private void classConvert(MapperFactory mapperFactory){
        mapperFactory.classMap(OriginClass.Std.class, TargetClass.Student.class)
                .field("stdname", "name")
                .field("stdid", "id")
                .fieldMap("time", "time").converter("stringDateConverter").add()
                .byDefault()
                .register();

        mapperFactory.classMap(OriginClass.class, TargetClass.class)
                .field("classid", "id")
                .field("classname", "className")
                .fieldMap("date", "time").converter("stringDateConverter").add()
                .field("num", "number")
                .field("stds", "students")
                .fieldMap("code", "codeEnum").converter("codeEnumConvert").add()
                .field("tea", "teacher")
                .byDefault().register();
    }

}
